const fs = require('fs');
const path = require('path');
const Config = require('./Config.js');
const {getSongIdFromUrl} = require('./Helper.js');

class IgnoreSong {

    /** -------------------- 私有辅助方法 -------------------- */

    static #ensureDir() {
        if (!fs.existsSync(Config.ignoreSongIdsDir)) {
            fs.mkdirSync(Config.ignoreSongIdsDir, { recursive: true });
        }
    }

    static #getFilePath(songId) {
        return path.resolve(Config.ignoreSongIdsDir, `${songId}.txt`);
    }

    static #writeFile(songId, data = '') {
        const file = this.#getFilePath(songId);
        fs.writeFileSync(file, data, 'utf8');
    }

    /** -------------------- 对外接口 -------------------- */

    static hasBySongId(songId) {
        this.#ensureDir();
        return fs.existsSync(this.#getFilePath(songId));
    }

    static hasByUrl(url) {
        const songId = getSongIdFromUrl(url);
        return this.hasBySongId(songId);
    }

    static ignoreBySongId(songId, log = '') {
        this.#ensureDir();
        this.#writeFile(songId, log);
    }

    static ignoreByUrl(url, log = '') {
        const songId = getSongIdFromUrl(url);
        this.ignoreBySongId(songId, log);
    }

    static deleteAll() {
        if (!fs.existsSync(Config.ignoreSongIdsDir)) return;
        fs.rmSync(Config.ignoreSongIdsDir, { recursive: true, force: true });
    }
}

module.exports = IgnoreSong;
